package service

import (
	"context"
	"errors"

	"github.com/example/video_backend/internal/model"
	"github.com/example/video_backend/internal/repository"
)

// CategoryService 分类服务接口
type CategoryService interface {
	// 创建分类
	CreateCategory(ctx context.Context, name, description string, userID uint) (*model.Category, error)
	// 根据ID获取分类
	GetCategoryByID(ctx context.Context, id uint) (*model.Category, error)
	// 获取所有分类
	GetAllCategories(ctx context.Context) ([]*model.Category, error)
	// 更新分类
	UpdateCategory(ctx context.Context, id uint, name, description string, userID uint) (*model.Category, error)
	// 删除分类
	DeleteCategory(ctx context.Context, id uint) error
	// 检查分类下是否有视频
	HasVideos(ctx context.Context, id uint) (bool, error)
}

// categoryService 实现CategoryService接口
type categoryService struct {
	categoryRepo repository.CategoryRepository
	videoRepo    repository.VideoRepository
}

// NewCategoryService 创建分类服务实例
func NewCategoryService(categoryRepo repository.CategoryRepository, videoRepo repository.VideoRepository) CategoryService {
	return &categoryService{
		categoryRepo: categoryRepo,
		videoRepo:    videoRepo,
	}
}

// CreateCategory 创建分类
func (s *categoryService) CreateCategory(ctx context.Context, name, description string, userID uint) (*model.Category, error) {
	// 检查分类名称是否为空
	if name == "" {
		return nil, errors.New("分类名称不能为空")
	}

	// 创建分类
	category := &model.Category{
		Name:        name,
		Description: description,
	}

	err := s.categoryRepo.Create(ctx, category)
	if err != nil {
		return nil, err
	}

	return category, nil
}

// GetCategoryByID 根据ID获取分类
func (s *categoryService) GetCategoryByID(ctx context.Context, id uint) (*model.Category, error) {
	return s.categoryRepo.GetByID(ctx, id)
}

// GetAllCategories 获取所有分类
func (s *categoryService) GetAllCategories(ctx context.Context) ([]*model.Category, error) {
	return s.categoryRepo.GetAll(ctx)
}

// UpdateCategory 更新分类
func (s *categoryService) UpdateCategory(ctx context.Context, id uint, name, description string, userID uint) (*model.Category, error) {
	// 检查分类是否存在
	category, err := s.categoryRepo.GetByID(ctx, id)
	if err != nil {
		return nil, err
	}
	if category == nil {
		return nil, errors.New("分类不存在")
	}

	// 更新分类信息
	if name != "" {
		category.Name = name
	}
	if description != "" {
		category.Description = description
	}

	err = s.categoryRepo.Update(ctx, category)
	if err != nil {
		return nil, err
	}

	return category, nil
}

// DeleteCategory 删除分类
func (s *categoryService) DeleteCategory(ctx context.Context, id uint) error {
	// 检查分类是否存在
	category, err := s.categoryRepo.GetByID(ctx, id)
	if err != nil {
		return err
	}
	if category == nil {
		return errors.New("分类不存在")
	}

	// 删除分类
	return s.categoryRepo.Delete(ctx, id)
}

// HasVideos 检查分类下是否有视频
func (s *categoryService) HasVideos(ctx context.Context, id uint) (bool, error) {
	return s.videoRepo.HasVideosByCategory(ctx, id)
}